package net.lzzy.lxq.controller;

import net.lzzy.lxq.config.WebSocketServer;
import net.lzzy.lxq.entities.*;
import net.lzzy.lxq.server.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ClockInController {

    //@Autowired
    //WebSocketServer socketServer;
    @Autowired
    WorkScheduleService scheduleService;
    @Autowired
    MonitorDeviceService monitorDeviceService;
    @Autowired
    UserDeviceService deviceService;
    @Autowired
    AttendanceService attendanceService;
    @Autowired
    UserService userService;
    @Autowired
    QRCodeService qrCodeService;

    //@SendTo("/remote/monitor2")
    //@MessageMapping("/sendTest")
    public Map<String,String> subTest1(String text){
        Map<String,String> map=new HashMap<>();
        map.put("result","local host：跑得快不一定赢，不被跌倒才是成功！");
        System.out.println("subTest1订阅:"+text);
        return map;
    }

    ///@SendTo("/remote/monitor")
    //@MessageMapping("/client")
    public Map<String, String> subTest2(String text){
        Map<String,String> map=new HashMap<>();
        map.put("result",":打卡成功");
        System.out.println("deviceid and monitorid:"+text);
        return map;
    }

    @GetMapping("/socket_test")
    public Map<String,String> socketTest(){
        Map<String,String> map=new HashMap<>();
        map.put("code","success");
        //socketServer.sendMessage("dddd");
        return map;
    }

    @PostMapping("/by_bluetooth")
    public Map<String,Object> clockInByBluetooth(@RequestBody Map<String,String> clockInMap){
        Map<String,Object> resultMap=new HashMap<>();
        MonitorDevice monitorDevice=monitorDeviceService.getMonitorDeviceByAddress(clockInMap.get("address"));
        UserDevice userDevice=deviceService.getUserDeviceByDeviceId(clockInMap.get("deviceId"));
        if (monitorDevice==null||userDevice==null){
            resultMap.put("code",1);
            resultMap.put("msg","设备ID错误");
            return resultMap;
        }
        return commonClickIn("蓝牙",clockInMap.get("name"),clockInMap.get("userId"),clockInMap.get("deviceId"));
    }

    @PostMapping("/by_qr_code")
    public Map<String,Object> clockInByQRCode(@RequestBody Map<String,String> param){
        Map<String,Object> result=new HashMap<>();
        UserDevice userDevice=deviceService.getUserDeviceByDeviceId(param.get("deviceId"));
        MonitorDevice monitorDevice=monitorDeviceService.getMonitorDevice(param.get("monitorDeviceId"));
        UserBean userBean=userService.getUser(param.get("userId"),param.get("password"));
        if (userBean==null||userDevice==null||monitorDevice==null){
            result.put("code",1);
            result.put("msg","设备ID错误或工号密码错误");
            return result;
        }
        if (param.get("random")==null){
            result.put("code",2);
            result.put("msg","二维码错误");
            return result;
        }
        QRCode qrCode=qrCodeService.getQRCodeConfig();
        if (qrCode.getRandom().equals(param.get("random"))){
            return commonClickIn("扫码",param.get("name"),param.get("userId"),param.get("deviceId"));
        }else{
            result.put("code",2);
            result.put("msg","二维码错误");
            return result;
        }
    }

    private Map<String,Object> commonClickIn(String deviceType, String name, String userId, String deviceId){
        Map<String,Object> resultMap=new HashMap<>();
        WorkSchedule schedule=scheduleService.getWorkSchedule();
        Calendar nowCalendar=Calendar.getInstance();

        Attendance attendance=new Attendance();
        attendance.setDeviceId(deviceId);
        attendance.setName(name);
        attendance.setUserId(userId);
        attendance.setSwipeDevice(deviceType);
        attendance.setSwipeTime(nowCalendar.getTime().getTime());

        Calendar afternoonWork=Calendar.getInstance();
        afternoonWork.set(Calendar.HOUR_OF_DAY,schedule.getAfternoonHour());
        afternoonWork.set(Calendar.MINUTE,schedule.getAfternoonMinute());
        if (afternoonWork.after(nowCalendar)){
            attendance.setSwipeType("上班");
            Calendar forenoonWorkCalendar=Calendar.getInstance();
            forenoonWorkCalendar.set(Calendar.HOUR_OF_DAY,schedule.getForenoonHour());
            forenoonWorkCalendar.set(Calendar.MINUTE,schedule.getForenoonMinute());

            Calendar startForenoonClockIn=Calendar.getInstance();
            startForenoonClockIn.set(Calendar.HOUR_OF_DAY,schedule.getForenoonClockInRangeHour());
            startForenoonClockIn.set(Calendar.MINUTE,schedule.getForenoonClockInRangeMinute());

            boolean check=attendanceService.checkSwipeType(userId,"上班");
            if(check){
                resultMap.put("code",2);
                resultMap.put("msg","你已经打了上班卡");
            }else if(nowCalendar.after(forenoonWorkCalendar)){
                attendance.setNegative("迟到");
                resultMap.put("code",0);
                resultMap.put("msg","打卡成功，您已迟到");
                attendanceService.add(attendance);
            }else if(nowCalendar.before(startForenoonClockIn)){
                resultMap.put("code",3);
                resultMap.put("msg","未到上班打卡时间");
            }else{
                attendance.setNegative("无");
                resultMap.put("code",0);
                resultMap.put("msg","打卡成功");
                attendanceService.add(attendance);
            }
        }else{
            Calendar finalClockInCalender=Calendar.getInstance();
            finalClockInCalender.set(Calendar.HOUR_OF_DAY,schedule.getAfternoonClockInRangeHour());
            finalClockInCalender.set(Calendar.MINUTE,schedule.getAfternoonClockInRangeMinute());
            if (nowCalendar.after(finalClockInCalender)){
                resultMap.put("code",4);
                resultMap.put("msg","超过下班打卡时间");
            }else{
                attendance.setSwipeType("下班");
                boolean check = attendanceService.checkSwipeType(userId, "下班");
                if (check) {
                    resultMap.put("code", 2);
                    resultMap.put("msg", "你已经打了下班卡");
                }else{
                    attendance.setNegative("无");
                    resultMap.put("code",0);
                    resultMap.put("msg","打卡成功");
                    attendanceService.add(attendance);
                }
            }
        }
        return resultMap;
    }
}
